package com.ow.dva.util.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


/**
 * java后台极光推送方式二：使用Java SDK
 */
@SuppressWarnings({ "deprecation", "restriction" })
public class JiguangPush {
    private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);

    //帐号信息
    //帐号:369809051@qq.com
    //密码:Ruitu110
    private static String masterSecret = "79650db0c6fa3e99eb42b2e7";
    private static String appKey = "f636399c966149b7b63475f6";



    public static void main(String[] args) {
        String alias = "*************";//声明别名(id) alias1
        String alert ="这是推送的内容";
        //自定义携带的东西
        Map<String,String> map = new HashMap();
        map.put("name","**");
        map.put("phone","********");
        map.put("id","123456");
        JSONObject jsonObject = JSONObject.fromObject(map);
        String jsonStr = jsonObject.toString();
        PushResult result = push(String.valueOf(alias),alert,jsonStr,"1");
        if(result != null && result.isResultOK()){
            log.info("针对别名" + alias + "的信息推送成功！");
        }else{
            log.info("针对别名" + alias + "的信息推送失败！");
        }
    }


    /**
     * 极光推送 推送给指定的用户
     */
    public void jiguangPush(String alias,String alert,String jsonStr,String type){
        PushResult result = push(String.valueOf(alias),alert,jsonStr,type);
        if(result != null && result.isResultOK()){
            log.info("针对别名" + alias + "的信息推送成功！");
        }else{
            log.info("针对别名" + alias + "的信息推送失败！");
        }
    }

    /**
     * 极光推送 推送给指定的用户
     * @param alias
     * @param alert
     * @param jsonStr
     * @param type 1-新订单 2-支付宝支付成功 3-微信支付成功
     */
    public static void jpush(String alias,String alert,String jsonStr,String type){
        PushResult result = push(String.valueOf(alias),alert,jsonStr,type);
        if(result != null && result.isResultOK()){
            log.info("针对别名" + alias + "的信息推送成功！");
        }else{
            log.info("针对别名" + alias + "的信息推送失败！");
        }
    }


    /**
     * 极光推送方法
     * @param alias
     * @param alert
     * @return PushResult
     */
    public static PushResult push(String alias,String alert,String jsonStr,String type){
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        PushPayload payload = buildPushObject_android_ios_alias_alert(alias,alert,jsonStr,type);
        try {
            return jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
            return null;
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
            return null;
        }
    }


    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     * 推送平台android和ｉos
     * @param alias
     * @param alert
     * @return PushPayload
     */
    public static PushPayload buildPushObject_android_ios_alias_alert(String alias,String alert,String result,String type){
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(alert)
                                .addExtra("message",result)
                                .addExtra("type",type)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("message",result)
                                .addExtra("type",type)//消息的类型
                                .setAlert(alert)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }

    public static PushPayload buildPushObject_all_alias_alert(String alert) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias("alias1"))
                .setNotification(Notification.alert(alert))
                .build();
    }


    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     * 推送平台android
     * @param alias
     * @param alert
     * @return PushPayload
     */
    public static PushPayload buildPushObject_android(String alias,String alert,String result,String type){
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(alert)
                                .addExtra("message",result)
                                .addExtra("type",type)
                                .build())
                      /*  .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("message",result)
                                .addExtra("type",type)//消息的类型
                                .setAlert(alert)
                                .build())*/
                        .build())
   /*             .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())*/
                .build();
    }




}